/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package SeparadorUrls;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Demon
 */
public class Utility {

    private static Pattern pattern;
    private static Matcher matcher;
    private static final String URL_WWW = "^((http|https)://)?(www\\.)?([a-zA-Z0-9\\./-]){1,}(com|org)([a-zA-Z0-9-/_\\.])*";

    /**
     *
     * @param url
     * @return
     */
    public static URL regresaURL(String url) {
         pattern = Pattern.compile(URL_WWW);

        if (validacionCustom(url)) {
            return validacionRequestMethod(url);
        }

        return null;
    }

    /**
     *
     * @param url
     * @return
     */
    private static boolean validacionCustom(String url) {

        matcher = pattern.matcher(url);
        return matcher.matches();
    }

    /**
     * 
     * @param url
     * @return
     */
    private static URL validacionRequestMethod(String url) {
        try {
            try {
                HttpURLConnection conexion = (HttpURLConnection) new URL(url).openConnection();
                conexion.setRequestMethod("HEAD");
                int codigo = conexion.getResponseCode();
                if (codigo == 200) {
                    return new URL(url);
                }
            } catch (MalformedURLException ex) {
                Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
                return null;
            }
        } catch (IOException ex) {
            Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
        return null;
    }
}
